package com.zhudoo.zhilian.service;

import com.alibaba.fastjson.JSON;
import com.zhudoo.zhilian.dao.entity.Appointment;
import com.zhudoo.zhilian.dao.entity.Tip;
import com.zhudoo.zhilian.dao.entity.User;
import com.zhudoo.zhilian.dao.impl.AppointmentDao;
import com.zhudoo.zhilian.dao.impl.TipDao;
import com.zhudoo.zhilian.dao.impl.UserDao;
import com.zhudoo.zhilian.util.service.ChatUtil;
import com.zhudoo.zhilian.util.web.BusinessException;
import com.zhudoo.zhilian.util.web.ServiceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author zhudao
 */
@Service
public class AppointmentService {

    //1.发起约看请求，2.同意约看，3.取消约看，4.约看满意，5.约看不满意
    /**
     * 发起约看请求
     */
    public static int APPOINTMENT_STATUS_1 = 1;
    /**
     * 同意约看
     */
    public static int APPOINTMENT_STATUS_2 = 2;
    /**
     * 拒绝约看
     */
    public static int APPOINTMENT_STATUS_3 = 3;
    /**
     * 约看满意
     */
    public static int APPOINTMENT_STATUS_4 = 4;
    /**
     * 约看不满意
     */
    public static int APPOINTMENT_STATUS_5 = 5;


    public static Map STATUS_MAP = new HashMap() {{
        put(APPOINTMENT_STATUS_1, "待处理");
        put(APPOINTMENT_STATUS_2, "同意约看");
        put(APPOINTMENT_STATUS_3, "取消约看");
        put(APPOINTMENT_STATUS_4, "约看满意");
        put(APPOINTMENT_STATUS_5, "约看不满意");
    }};

    @Autowired
    private AppointmentDao appointmentDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private TipDao tipDao;

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> sendAppointment(ServiceContext serviceContext) {
        Map<String, Object> resultMap = new HashMap<>(10);
        String token = serviceContext.getParamsString("token");
        Integer toUserId = serviceContext.getParamsInteger("toUserId");
        Integer tipId = serviceContext.getParamsInteger("tipId");
        Date appointmentDate = serviceContext.getParamsDate("appointmentDate");
        String address = serviceContext.getParamsString("address");
        String name = serviceContext.getParamsString("name");
        String phone = serviceContext.getParamsString("phone");
        User user = userDao.findUserByToken(token);
        Tip tip = tipDao.getTipById(tipId);
        if (tip == null) {
            throw BusinessException.getInstance("帖子不存在");
        }
        String onlyStr = ChatUtil.getOnlyStr(user.getId(), toUserId, appointmentDate, address, name, phone);
        Appointment appointment = appointmentDao.getAppointmentByOnlyStr(onlyStr);
        if (appointment == null) {
            appointment = new Appointment();
            appointment.setCreateTime(new Date());
            appointment.setUserId(user.getId());
            appointment.setToUserId(toUserId);
            appointment.setTipId(tipId);
            appointment.setAppointmentDate(appointmentDate);
            appointment.setAddress(address);
            appointment.setName(name);
            appointment.setPhone(phone);
            appointment.setStatus(APPOINTMENT_STATUS_1);
            appointment.setValid(true);
            appointment.setUpdateTime(new Date());
            appointmentDao.saveAppointment(appointment);
            resultMap.put("appointmentId", appointment.getId());
        } else {
            throw BusinessException.getInstance("约看已发送");
        }
        return resultMap;
    }

    public List<Map<String, Object>> getAppointmentList(ServiceContext serviceContext) {
        List<Map<String, Object>> resultList = new ArrayList<>(10);
        String token = serviceContext.getParamsString("token");
        Integer status = serviceContext.getParamsInteger("status");
        Integer page = serviceContext.getPage();
        Integer limit = serviceContext.getLimit();
        User user = userDao.findUserByToken(token);
        List<Appointment> appointments = appointmentDao.getAppointmentList(user.getId(), user.getType(), status, page, limit);
        for (Appointment appointment : appointments) {
            Map<String, Object> resultMap = new HashMap<>(10);
            if (user.getType() == UserService.TYPE_1) {
                User user1 = userDao.findUserById(appointment.getUserId());
                resultMap.put("nickName", user1.getNickName());
                resultMap.put("headImg", user1.getHeadImg());
            } else {
                User user1 = userDao.findUserById(appointment.getToUserId());
                resultMap.put("nickName", user1.getNickName());
                resultMap.put("headImg", user1.getHeadImg());
            }
            resultMap.put("status", appointment.getStatus());
            resultMap.put("statusName", STATUS_MAP.get(appointment.getStatus()));
            resultMap.put("id", appointment.getId());
            resultMap.put("appointmentDate", appointment.getAppointmentDate());
            resultMap.put("address", JSON.parseObject(appointment.getAddress()));
            resultList.add(resultMap);
        }
        return resultList;
    }

    public Map<String, Object> getAppointmentById(ServiceContext serviceContext) {
        Map<String, Object> resultMap = new HashMap<>(10);
        String token = serviceContext.getParamsString("token");
        Integer id = serviceContext.getParamsInteger("id");
        User user = userDao.findUserByToken(token);
        Appointment appointment = appointmentDao.getAppointmentById(id);
        if (appointment.getUserId().intValue() == user.getId() || appointment.getToUserId().intValue() == user.getId()) {
            resultMap.put("name", appointment.getName());
            resultMap.put("phone", appointment.getPhone());
            resultMap.put("appointmentDate", appointment.getAppointmentDate());
            resultMap.put("address", JSON.parseObject(appointment.getAddress()));
            resultMap.put("tipId", appointment.getTipId());
            resultMap.put("status", appointment.getStatus());
            resultMap.put("statusName", STATUS_MAP.get(appointment.getStatus()));
            resultMap.put("id", appointment.getId());

            //租客信息
            Map<String, Object> renterInfo = new HashMap<>(4);
            User user1 = userDao.findUserById(appointment.getToUserId());
            renterInfo.put("nickName", user1.getNickName());
            renterInfo.put("sex", user1.getSex());
            renterInfo.put("headImg", user1.getHeadImg());
            if (appointment.getStatus() != APPOINTMENT_STATUS_1 && appointment.getStatus() != APPOINTMENT_STATUS_3) {
                renterInfo.put("phone", user1.getPhone());
            }
            renterInfo.put("userId", user1.getId());
            resultMap.put("renterInfo", renterInfo);

            //房东信息
            Map<String, Object> landlordInfo = new HashMap<>(3);
            User user2 = userDao.findUserById(appointment.getUserId());
            landlordInfo.put("nickName", user2.getNickName());
            landlordInfo.put("sex", user2.getSex());
            landlordInfo.put("headImg", user2.getHeadImg());
            landlordInfo.put("userId", user2.getId());
            resultMap.put("landlordInfo", landlordInfo);
        }
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateAppointment(ServiceContext serviceContext) {
        String token = serviceContext.getParamsString("token");
        Integer id = serviceContext.getParamsInteger("id");
        Integer status = serviceContext.getParamsInteger("status");
        User user = userDao.findUserByToken(token);
        Appointment appointment = appointmentDao.getAppointmentById(id);
        if (appointment.getStatus().intValue() == status) {
            throw BusinessException.getInstance("提交成功");
        }
        if (user.getId().intValue() == appointment.getToUserId()) {
            appointment.setStatus(status);
            appointmentDao.saveAppointment(appointment);
        }
    }
}
